package cn.com.header.core.support.web.springmvc.converter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter4;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.converter.HttpMessageNotWritableException;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Type;

/**
 * @author liangzhongqiu789@sina.com
 * @date 2017-05-11
 * @time 14:35
 */
public class FastJsonHttpMessageConverter extends FastJsonHttpMessageConverter4 {


    /**
     * 修复 FastJsonHttpMessageConverter4 无法将Enum类输出为 Enum.ordinal()的缺陷
     * @param obj
     * @param type
     * @param outputMessage
     * @throws IOException
     * @throws HttpMessageNotWritableException
     */
    @Override
    protected void writeInternal(Object obj, //
                                 Type type, //
                                 HttpOutputMessage outputMessage //
    ) throws IOException, HttpMessageNotWritableException {

        HttpHeaders headers = outputMessage.getHeaders();
        ByteArrayOutputStream outnew = new ByteArrayOutputStream();
        FastJsonConfig fastJsonConfig = getFastJsonConfig();
        SerializerFeature[] serializerFeatures = fastJsonConfig.getSerializerFeatures();
        int features = 0;
        if(serializerFeatures.length > 0){
            for(SerializerFeature serializerFeature : serializerFeatures){
                features |= serializerFeature.getMask();
            }
        }else {
            features = JSON.DEFAULT_GENERATE_FEATURE;
        }
        int len = JSON.writeJSONString(outnew, //
                fastJsonConfig.getCharset(), //
                obj, //
                fastJsonConfig.getSerializeConfig(), //
                fastJsonConfig.getSerializeFilters(), //
                fastJsonConfig.getDateFormat(), //
                features, //
                fastJsonConfig.getSerializerFeatures());
        headers.setContentLength(len);
        OutputStream out = outputMessage.getBody();
        outnew.writeTo(out);
        outnew.close();
    }

}
